﻿@using si.caha.Repository;
@using si.caha.Helper;
@using si.caha.Model;

@{
    Layout = "~/tpl/_layout.cshtml";
    PageData["PageTitle"] = "Your shopping cart";
    
    var disabledAttribute = "";
    var items = new string[0];
    var itemIds = new int[0];

    if(Validator.isCookieFilled(Request.Cookies))
    {
        items = Request.Cookies["cart"]["items"].Split(',');
        itemIds = items.Select(x => int.Parse(x)).ToArray();
    }
    
    if (itemIds.Length == 0)
    {
        disabledAttribute = "disabled";
    }
    
    DataContext dataContext = new DataContext();
    var itemRepository = new ItemRepository(dataContext);
    var itemsList = new List<Item>();
    
    foreach(var itemId in itemIds)
    {
        itemsList.Add(itemRepository.Get(itemId));
    }
    
    if (IsPost)
    {
        // ItemId, Quantity
        var orderItems = new Dictionary<int, int>();
        foreach(var itemId in itemIds)
        {
            orderItems.Add(itemId, Request[itemId.ToString()].AsInt());
        }
        
        Session["Items"] = orderItems;
        Response.Redirect("~/Cart/Checkout");
    }
}
<script>
    $(function(){
        $("li > button").click(function(){
            var itmId = $(this).attr("id");
            // ajax post
            $.post("/Cart/partial/removeFromCart.cshtml", { itemId: itmId }, 
                // success
                function(){
                    $("li#" + itmId).hide();
                    var cartItemsCount = parseInt($("#cartItemsCount").html());
                    cartItemsCount--;
                    $("#cartItemsCount").html(cartItemsCount);
                    
                    if (cartItemsCount == 0){
                        $("#checkoutButton").attr("disabled", "disabled");
                    }
            });
        });
    });
</script>
<div>
    <form method="post">
        <ul>
        @foreach(var item in itemsList)
        {
            var categories = CategoryHierarchy.GetCategorieshierarchyFromItem(item);
            <li id="@item.ItemId">
                <a href="@Href("~/Store" + @categories + "/Item/" + @item.ItemId)">@item.Title</a>
                <span>€ @item.Price</span>
                <label for="quantity">Quantity</label>
                <input type="number" id="@item.ItemId" name="@item.ItemId" min="1" max="10" size="2" value="1" />
                <button type="button" id="@item.ItemId">Remove</button>
            </li>
        }
        </ul>
        <a href="@Href("~/Store")">Countinuse shopping</a>   
        <button type="submit" id="checkoutButton" @disabledAttribute>Go to checkout</button>
    </form>
</div>